package com.p2p.account.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.p2p.account.po.Agent;
import com.p2p.account.service.AgentService;
import com.p2p.account.vo.AgentVo;
import com.p2p.common.base.BaseController;
import com.p2p.common.constants.Message;
import com.p2p.common.enums.ResponseEnum;
import com.p2p.common.token.TokenService;
import com.p2p.common.utils.MD5Encryption;
import com.p2p.common.utils.Underline2Camel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Allen on 2017/3/19.
 */
@RestController
@RequestMapping(value = "agent")
public class AgentController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(AgentController.class);
    @Autowired
    private AgentService agentService;
    @Resource
    private TokenService tokenService;

    /**
     * 获取用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectAgent", method = RequestMethod.GET)
    public Map selectAgent(HttpServletRequest request) {
        Integer pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String sortField = Underline2Camel.camel2Underline(request.getParameter("sort") == null ? "id" : request.getParameter("sort"), true);
        String orderField = request.getParameter("order") == null ? "desc" : request.getParameter("order");

        int startRow = (pageIndex - 1) * pageSize;
        List<AgentVo> userList = agentService.selectLists(startRow, pageSize, sortField, orderField);

        int size = agentService.selectList(new EntityWrapper<Agent>().eq("status", 1)).size();

        Map result = new HashMap();
        result.put("rel", true);
        result.put("msg", "SUCCESS");
        result.put("list", userList);
        result.put("count", size);
        return result;
    }


    /**
     * 获取代理商Select选项
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectAgentOption", method = RequestMethod.GET)
    public Message selectAgentOption(HttpServletRequest request) {
        Integer optionType = Integer.parseInt(request.getParameter("optionType"));
        List<Agent> agentList = new ArrayList<>();
        if (optionType == 1) {
            Integer level = Integer.parseInt(request.getParameter("level"));
            agentList = agentService.selectList(new EntityWrapper<Agent>().eq("status", 1).eq("agent_level", level));
        } else if (optionType == 0) {
            agentList = agentService.selectList(new EntityWrapper<Agent>().eq("status", 1));
        } else {
            Long oneLevelId = Long.parseLong(request.getParameter("oneLevelId"));
            agentList = agentService.selectList(new EntityWrapper<Agent>().eq("status", 1).eq("one_level_id", oneLevelId));
        }
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), agentList);
    }

    /**
     * 获取用户 By UserId
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectAgentById", method = RequestMethod.GET)
    public Message selectAgentById(HttpServletRequest request) {
        Long agentId = Long.parseLong(request.getParameter("agentId"));
        Agent agent = agentService.selectOne(new EntityWrapper<Agent>().eq("id", agentId));

        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), agent);
    }

    /**
     * 获取用户 By UserId
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectAgentLevelById", method = RequestMethod.GET)
    public Message selectAgentLevelById(HttpServletRequest request) {
        Long agentId = Long.parseLong(request.getParameter("agentId"));
        Agent agent = agentService.selectOne(new EntityWrapper<Agent>().eq("id", agentId));
        List<Agent> agentList = new ArrayList<>();
        if (agent.getAgentLevel() == 2) {
            Long oneLevelId = agent.getOneLevelId();
            agentList = agentService.selectList(new EntityWrapper<Agent>().eq("status", 1).eq("one_level_id", oneLevelId));

        }
        if (agent.getAgentLevel() == 3) {
            Long oneLevelId = agent.getOneLevelId();
            agentList = agentService.selectList(new EntityWrapper<Agent>().eq("status", 1).eq("one_level_id", oneLevelId));

        }

        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), agentList);
    }


    /**
     * 增加用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "insertAgent", method = RequestMethod.POST)
    public Message insertAgent(HttpServletRequest request, Agent agent) {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        if (agentService.selectOne(new EntityWrapper<Agent>().eq("username", agent.getUsername())) != null) {
            return new Message(ResponseEnum.USERNAME_IS_EXIST.getCode(), ResponseEnum.USERNAME_IS_EXIST.getMsg());
        }

        agent.setPassword(MD5Encryption.encrypt(agent.getPassword(), agent.getUsername()));
        agent.setCreateTime(timestamp);
        agentService.insert(agent);
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }


    /**
     * 增加用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "updateAgent", method = RequestMethod.POST)
    public Message updateAgent(HttpServletRequest request, Agent agent) {


        try {
            if (StringUtils.isNotEmpty(agent.getPassword())) {
                if (agent.getPassword().length() < 6) {
                    return new Message(4405, "密码长度小于6位");
                }
                agent.setPassword(MD5Encryption.encrypt(agent.getPassword(), agent.getUsername()));
            } else {
                agent.setPassword(null);
            }
            agentService.updateById(agent);
            return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());

        } catch (Exception e) {
            return new Message(ResponseEnum.SERVER_ERROR.getCode(), ResponseEnum.SERVER_ERROR.getMsg());
        }
    }

    /**
     * 逻辑删除用户
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "deleteAgent", method = RequestMethod.GET)
    public Message deleteAgent(HttpServletRequest request) {
        Long agentId = Long.parseLong(request.getParameter("agentId"));
        Agent agent = agentService.selectById(agentId);
        agent.setStatus(-1);
        agentService.updateById(agent);
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }


    /**
     * @param request
     * @return
     */
    @RequestMapping(value = "test", method = RequestMethod.GET)
    public Message test(HttpServletRequest request) {
        Long id = Long.parseLong(request.getParameter("id"));
        Agent agent = agentService.selectById(id);
        String token = tokenService.createToken(id,"p2p:agent:token:");
        Map<String, String> result = new HashMap<String, String>();
        result.put("t", token + "|" + agent.getAgentName());
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result);
    }
}
